package com.cnebula.uas.sso.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cnebula.uas.sso.ConfAdmin;
import com.cnebula.uas.sso.model.IdpAuthCenter;
import com.cnebula.uas.sso.service.IdpAuthCenterService;
import com.cnebula.uas.sso.service.IdpLoginValidService;

@Controller
@RequestMapping(value = "/sp")
public class SPLoginController {

	@Autowired
	IdpAuthCenterService idpAuthCenterService;
	
	@Autowired
	IdpLoginValidService idpLoginValidService;

	@Autowired
	ConfAdmin conf;

	@RequestMapping(value = "/idp/{idpCode}")
	@GetMapping
	public void splogin(@PathVariable String idpCode, HttpServletResponse response) throws Exception {

		IdpAuthCenter idpAuthCenter = idpAuthCenterService.getIdpAuthCenter(idpCode);
		String authURL = idpAuthCenter.authURL;
		String callbackURL = "http://" + conf.host + ":" + conf.port + "/sp/idp/" + idpCode + "/callback?verb=cb";

		URIBuilder authURLBuilder = new URIBuilder(authURL);
		authURLBuilder.addParameter("sp", callbackURL);
		authURLBuilder.addParameter("goto", "/index");
		authURLBuilder.addParameter("idp", idpCode);

		response.sendRedirect(authURLBuilder.build().toString());
	}

	@RequestMapping(value = "/idp/{idpCode}/callback", produces = "application/xml")
	@GetMapping
	public ResponseEntity<String> callback(@PathVariable String idpCode, @RequestParam String artifact,
			@RequestParam("goto") String gotoURL) throws Exception {
		
		String userInfo = idpLoginValidService.valid(idpCode, artifact);
		
		//TODO 暂时直接响应用户信息，待以后goto确定后跳转到goto地址
		return ResponseEntity.ok(userInfo);
	}
	
	@RequestMapping(value = "/idp/{idpCode}/valid")
	@GetMapping
	public String loginValid(String idpCode, String artifact) throws Exception {
		return null;
	}
}
